package com.blunka.framework.client.ui.dialog;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.tree.DefaultMutableTreeNode;

import org.apache.log4j.Logger;

import com.blunka.framework.client.constants.DesignConstant;
import com.blunka.framework.client.db.druid.DBSQLService;
import com.blunka.framework.client.enums.ModelStates;
import com.blunka.framework.client.ui.AttrPanel;
import com.blunka.framework.client.ui.MainFrame;
import com.blunka.framework.client.ui.TreeModelPanel;
import com.blunka.framework.client.ui.entity.BlkTableMetaData;
import com.blunka.framework.client.utils.DesignUtils;
/**
 *
 *
 * @平台：统一开发平台
 * @文件名称：SubmitDialog.java
 * @文件描述：提交系统业务建模
 * @author xuqiang
 * @日期：2018年5月28日下午3:44:46
 *
 */
public class SubmitDialog extends JDialog implements Runnable{

	private static final Logger logger = Logger.getLogger(SubmitDialog.class);

	private Thread splashThread; // 进度条更新线程

	private JProgressBar progress; // 进度条

	/**
	 * 进度条图片
	 */
	private JLabel progressImageLabel;

	/**
	 * 提交成功的数据
	 */
	private List<String> execute_all_success_data ;
	
	private boolean IS_INIT_DBSERVER = false;
	
	private String submit_type;
	
	/**
	 * 提交方式，所有包括数据库表结构
	 */
	public static final String SUBMIT_TYPE_ALL = "all";
	
	/**
	 * 只提交业务模型
	 */
	public static final String SUBMIT_TYPE_BUSINESS_MODEL = "business_model";
	
	/**
	 * 
	 * @param IS_INIT_DBSERVER 是否初始化数据库提交的业务模型
	 */
	public SubmitDialog(boolean IS_INIT_DBSERVER) {
		this.IS_INIT_DBSERVER = IS_INIT_DBSERVER;
	}

	/**
	 * @param submit_type提交方式
	 */
	public SubmitDialog(String submit_type){
		this.submit_type = submit_type;
		Container container = getContentPane();
		setTitle("提交业务数据");
		setSize(new Dimension(350, 120));
		//setUndecorated(true);
		String url = DesignUtils.getDir()+"/res/images/timer.jpg"; // 图片的位置
		progressImageLabel = new JLabel();
		progressImageLabel.setIcon(new ImageIcon(url));
		container.add(progressImageLabel, BorderLayout.NORTH); // 增加图片
		progress = new JProgressBar(1,100); // 实例化进度条
        progress.setStringPainted(true); // 描绘文字
        progress.setString("正在提交服务器,请稍候......"); // 设置显示文字
        progress.setBackground(Color.white); // 设置背景色
        container.add(progress, BorderLayout.SOUTH); // 增加进度条到容器上
		splashThread = new Thread(this); // 实例化线程
        splashThread.start(); // 开始运行线程
		setModal(true);
		setLocationRelativeTo(MainFrame.getMainFrame());
		setVisible(true);
	}

	public void run(){
		if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
			submitAll();
		}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
			submitBusinessModel();
		}
	}
	
	/**
	 * 提交所有业务，包括数据库结构和模型数据
	 */
	private void submitAll() {
		try{
			//表示为全部提交还是部分数据提交
			boolean is_all_submit = false;
			execute_all_success_data = new ArrayList<String>();
			if(!updateModelTable()){
				if(!updateModelField()){
					if(!updateModelNode()){
						logger.info("业务建模提交服务器成功");
						if(IS_INIT_DBSERVER == false) {
							DesignUtils.showMessage(this, "提交服务器成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						}
						dispose();
						is_all_submit = true;
					}
				}
			}
			refreshModelTree(is_all_submit);
			if(!is_all_submit){
				//提交成功了部分数据
				DesignUtils.showMessage(this, "提交数据库失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
			}
		}catch(Exception e){
			logger.error("提交服务器数据异常",e);
			DesignUtils.showMessage(this, "提交数据库失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}finally {
			dispose();
		}
	}
	
	/**
	 * 只提交业务模型数据，不提交数据库表结构
	 */
	private void submitBusinessModel() {
		try{
			//表示为全部提交还是部分数据提交
			boolean is_all_submit = false;
			execute_all_success_data = new ArrayList<String>();
			if(!updateModelTable()){
				if(!updateModelField()){
					if(!updateModelNode()){
						logger.info("业务建模提交服务器成功");
						if(IS_INIT_DBSERVER == false) {
							DesignUtils.showMessage(this, "提交服务器成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						}
						dispose();
						is_all_submit = true;
					}
				}
			}
			refreshModelTree(is_all_submit);
			if(!is_all_submit){
				//提交成功了部分数据
				DesignUtils.showMessage(this, "提交数据库失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
			}
		}catch(Exception e){
			logger.error("提交服务器数据异常",e);
			DesignUtils.showMessage(this, "提交数据库失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}finally {
			dispose();
		}
	}

	/**
	 * 表节点操作
	 * @return
	 */
	private boolean updateModelTable(){
		//记录执行成功的数据ID，最后统一更新
		List<String> execute_success_data = new ArrayList<String>();
		//删除数据
		List<String> execute_delete_data = new ArrayList<String>();
		//操作是否存在错误
		boolean is_execute_error = false;
		logger.info("正在同步服务器表结构");
		//新增表
		try{
			//查询所有的新建表数据
			List<BlkTableMetaData> newTableMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE IN('4','5') AND MODEL_STATES ='1'", BlkTableMetaData.class);
			for(BlkTableMetaData tableMetaData : newTableMetaDataList){
				//创建表
				tableMetaData.setModel_states(ModelStates.FINISHED);
				//DBSQLService.getDBService().insertTableNode(tableMetaData);
				if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
					//提交全部包括数据库和业务数据
					DBSQLService.getDBService().insertTableNode(tableMetaData);
				}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
					//只提交业务数据
					DBSQLService.getDBService().insertTableNodeModel(tableMetaData);
				}
				execute_success_data.add(tableMetaData.getTablemetadata_id());
				execute_all_success_data.add(tableMetaData.getTablemetadata_id());
			}
		}catch(Exception e){
			logger.error("同步服务器表结构失败",e);
			is_execute_error = true;
		}finally{
			//更新本地缓存数据库模型状态为完成状态
			updateModelMetaDataFinished(execute_success_data);
			execute_success_data.clear();
		}

		//修改表
		if(!is_execute_error){
			try{
				//查询所有的新建表数据
				List<BlkTableMetaData> newTableMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE IN('4','5') AND MODEL_STATES ='2'", BlkTableMetaData.class);
				for(BlkTableMetaData tableMetaData : newTableMetaDataList){
					//创建表
					tableMetaData.setModel_states(ModelStates.FINISHED);
					//DBSQLService.getDBService().updateTableNode(tableMetaData);
					if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
						//提交全部包括数据库和业务数据
						DBSQLService.getDBService().updateTableNode(tableMetaData);
					}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
						//只提交业务数据
						DBSQLService.getDBService().updateTableNodeModel(tableMetaData);
					}
					execute_success_data.add(tableMetaData.getTablemetadata_id());
					execute_all_success_data.add(tableMetaData.getTablemetadata_id());
				}
			}catch(Exception e){
				logger.error("同步服务器表结构失败_",e);
				is_execute_error = true;
			}finally{
				//更新本地缓存数据库模型状态为完成状态
				updateModelMetaDataFinished(execute_success_data);
				execute_success_data.clear();
			}
		}
		//删除表
		if(!is_execute_error){
			try{
				//查询所有的新建表数据
				List<BlkTableMetaData> newTableMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE IN('4','5') AND MODEL_STATES ='4'", BlkTableMetaData.class);
				for(BlkTableMetaData tableMetaData : newTableMetaDataList){
					//创建表
					tableMetaData.setModel_states(ModelStates.FINISHED);
					//DBSQLService.getDBService().deleteTableNode(tableMetaData);
					if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
						//提交全部包括数据库和业务数据
						DBSQLService.getDBService().deleteTableNode(tableMetaData);
					}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
						//只提交业务数据
						DBSQLService.getDBService().deleteTableNodeModel(tableMetaData);
					}
					execute_delete_data.add(tableMetaData.getTablemetadata_id());
				}
			}catch(Exception e){
				logger.error("同步服务器表结构失败_@",e);
				is_execute_error = true;
			}finally{
				//更新本地缓存数据库模型状态为完成状态
				deleteModelMetaDataFinished(execute_delete_data);
				execute_success_data.clear();
			}
		}
		return is_execute_error;
	}

	/**
	 * 同步数据库字段信息
	 * @return
	 */
	private boolean updateModelField(){
		//记录执行成功的数据ID，最后统一更新
		List<String> execute_success_data = new ArrayList<String>();

		//删除数据
		List<String> execute_delete_data = new ArrayList<String>();
		//操作是否存在错误
		boolean is_execute_error = false;
		logger.info("正在同步服务器表结构字段");
		try{
			//新表或者试图字段
			List<BlkTableMetaData> newFieldMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE='6' AND MODEL_STATES ='1'", BlkTableMetaData.class);
			for(BlkTableMetaData fieldMetaData : newFieldMetaDataList){
				//所属父节点
				BlkTableMetaData parentBlkModel = DBSQLService.getLocalDBService().getDBUtils().getBean("SELECT * FROM BLK_TABLE_METADATA WHERE TABLEMETADATA_ID='"+fieldMetaData.getFather_tablemetadata_id()+"'", BlkTableMetaData.class);
				//创建表
				fieldMetaData.setModel_states(ModelStates.FINISHED);
				//DBSQLService.getDBService().insertField(fieldMetaData, parentBlkModel);
				if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
					//提交全部包括数据库和业务数据
					DBSQLService.getDBService().insertField(fieldMetaData, parentBlkModel);
				}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
					//只提交业务数据
					DBSQLService.getDBService().insertFieldModel(fieldMetaData, parentBlkModel);
				}
				execute_success_data.add(fieldMetaData.getTablemetadata_id());
				execute_all_success_data.add(fieldMetaData.getTablemetadata_id());
			}
		}catch(Exception e){
			is_execute_error = true;
			logger.error("同步表结构字段失败",e);
		}finally{
			//更新本地缓存数据库模型状态为完成状态
			updateModelMetaDataFinished(execute_success_data);
			execute_success_data.clear();
		}

		//修改字段
		if(!is_execute_error){
			try{
				//新表或者试图字段
				List<BlkTableMetaData> newFieldMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE='6' AND MODEL_STATES ='2'", BlkTableMetaData.class);
				for(BlkTableMetaData fieldMetaData : newFieldMetaDataList){
					//所属父节点
					BlkTableMetaData parentBlkModel = DBSQLService.getLocalDBService().getDBUtils().getBean("SELECT * FROM BLK_TABLE_METADATA WHERE TABLEMETADATA_ID='"+fieldMetaData.getFather_tablemetadata_id()+"'", BlkTableMetaData.class);
					//创建表
					fieldMetaData.setModel_states(ModelStates.FINISHED);
					//DBSQLService.getDBService().updateField(fieldMetaData, parentBlkModel);
					if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
						//提交全部包括数据库和业务数据
						DBSQLService.getDBService().updateField(fieldMetaData, parentBlkModel);
					}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
						//只提交业务数据
						DBSQLService.getDBService().updateFieldModel(fieldMetaData, parentBlkModel);
					}
					execute_success_data.add(fieldMetaData.getTablemetadata_id());
					execute_all_success_data.add(fieldMetaData.getTablemetadata_id());
				}
			}catch(Exception e){
				is_execute_error = true;
				logger.error("同步表结构字段失败_",e);
			}finally{
				//更新本地缓存数据库模型状态为完成状态
				updateModelMetaDataFinished(execute_success_data);
				execute_success_data.clear();
			}
		}
		//删除字段
		if(!is_execute_error){
			try{
				//新表或者试图字段
				List<BlkTableMetaData> newFieldMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE='6' AND MODEL_STATES ='4'", BlkTableMetaData.class);
				for(BlkTableMetaData fieldMetaData : newFieldMetaDataList){
					//所属父节点
					BlkTableMetaData parentBlkModel = DBSQLService.getLocalDBService().getDBUtils().getBean("SELECT * FROM BLK_TABLE_METADATA WHERE TABLEMETADATA_ID='"+fieldMetaData.getFather_tablemetadata_id()+"'", BlkTableMetaData.class);
					//创建表
					fieldMetaData.setModel_states(ModelStates.FINISHED);
					//DBSQLService.getDBService().deleteField(fieldMetaData, parentBlkModel);
					if(SUBMIT_TYPE_ALL.equals(this.submit_type)) {
						//提交全部包括数据库和业务数据
						DBSQLService.getDBService().deleteField(fieldMetaData, parentBlkModel);
					}else if(SUBMIT_TYPE_BUSINESS_MODEL.equals(this.submit_type)) {
						//只提交业务数据
						DBSQLService.getDBService().deleteFieldModel(fieldMetaData, parentBlkModel);
					}
					execute_delete_data.add(fieldMetaData.getTablemetadata_id());
				}
			}catch(Exception e){
				is_execute_error = true;
				logger.error("同步表结构字段失败_@",e);
			}finally{
				//更新本地缓存数据库模型状态为完成状态
				deleteModelMetaDataFinished(execute_delete_data);
				execute_success_data.clear();
			}
		}

		return is_execute_error;
	}

	/**
	 * 更新普通业务节点
	 * @return
	 */
	private boolean updateModelNode(){
		//记录执行成功的数据ID，最后统一更新
		List<String> execute_success_data = new ArrayList<String>();
		//删除数据
		List<String> execute_delete_data = new ArrayList<String>();
		//操作是否存在错误
		boolean is_execute_error = false;
		logger.info("正在同步服务器业务模型");
		try{
			//新表或者试图字段
			List<BlkTableMetaData> newFieldMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE IN('1','2','3','9') AND MODEL_STATES ='1'", BlkTableMetaData.class);
			for(BlkTableMetaData metaData : newFieldMetaDataList){
				//创建表
				metaData.setModel_states(ModelStates.FINISHED);
				DBSQLService.getDBService().insertNode(metaData);
				execute_success_data.add(metaData.getTablemetadata_id());
				execute_all_success_data.add(metaData.getTablemetadata_id());
			}
			//更新本地缓存数据库模型状态为完成状态
			updateModelMetaDataFinished(execute_success_data);
			execute_success_data.clear();
		}catch(Exception e){
			is_execute_error = true;
			logger.error("同步服务器业务模型失败",e);
		}

		//修改
		if(!is_execute_error){
			try{
				//新表或者试图字段
				List<BlkTableMetaData> newFieldMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE IN('1','2','3','9') AND MODEL_STATES ='2'", BlkTableMetaData.class);
				for(BlkTableMetaData metaData : newFieldMetaDataList){
					//创建表
					metaData.setModel_states(ModelStates.FINISHED);
					DBSQLService.getDBService().updateNode(metaData);
					execute_success_data.add(metaData.getTablemetadata_id());
					execute_all_success_data.add(metaData.getTablemetadata_id());
				}
				updateModelMetaDataFinished(execute_success_data);
				execute_success_data.clear();
			}catch(Exception e){
				is_execute_error = true;
				logger.error("同步服务器业务模型失败_",e);
			}
		}

		//删除
		if(!is_execute_error){
			try{
				//新表或者试图字段
				List<BlkTableMetaData> newFieldMetaDataList = DBSQLService.getLocalDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA WHERE MODEL_TYPE IN('1','2','3','9') AND MODEL_STATES ='4'", BlkTableMetaData.class);
				for(BlkTableMetaData metaData : newFieldMetaDataList){
					//创建表
					metaData.setModel_states(ModelStates.FINISHED);
					DBSQLService.getDBService().deleteNode(metaData);
					execute_delete_data.add(metaData.getTablemetadata_id());
				}
				//更新本地缓存数据库模型状态为完成状态
				deleteModelMetaDataFinished(execute_delete_data);
				execute_success_data.clear();
			}catch(Exception e){
				is_execute_error = true;
				logger.error("同步服务器业务模型失败_@",e);
			}
		}

		return is_execute_error;
	}


	/**
	 * 批量更新本地缓存模型数据状态为完成
	 * @param execute_success_data
	 */
	private void updateModelMetaDataFinished(List<String> execute_success_data_list){
		if(execute_success_data_list !=null && !execute_success_data_list.isEmpty() && execute_success_data_list.size()>0){
			StringBuffer updateSql = new StringBuffer("UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.FINISHED.getIndex()+"' WHERE TABLEMETADATA_ID in (");
			int i=0;
			for(String tablemetadata_id : execute_success_data_list){
				if(i==0){
					updateSql.append("'").append(tablemetadata_id).append("'");
				}else{
					updateSql.append(",'").append(tablemetadata_id).append("'");
				}
				i++;
			}
			updateSql.append(")");
			DBSQLService.getLocalDBService().getDBUtils().execute(updateSql.toString());
		}
	}

	/**
	 * 删除业务模型表中的标记为删除的数据
	 * @param execute_success_data_list
	 */
	private void deleteModelMetaDataFinished(List<String> execute_success_data_list){
		if(execute_success_data_list !=null && !execute_success_data_list.isEmpty() && execute_success_data_list.size()>0){
			StringBuffer updateSql = new StringBuffer("DELETE FROM BLK_TABLE_METADATA  WHERE TABLEMETADATA_ID in (");
			int i=0;
			for(String tablemetadata_id : execute_success_data_list){
				if(i==0){
					updateSql.append("'").append(tablemetadata_id).append("'");
				}else{
					updateSql.append(",'").append(tablemetadata_id).append("'");
				}
				i++;
			}
			updateSql.append(")");
			DBSQLService.getLocalDBService().getDBUtils().execute(updateSql.toString());
		}
	}

	/**
	 * 刷新全部数据
	 * @param parentNode
	 * @param isRoot
	 */
	private void refreshAllModelTree(DefaultMutableTreeNode parentNode,boolean isRoot){
		if(!isRoot){
			BlkTableMetaData tableMetaData = (BlkTableMetaData)parentNode.getUserObject();
			tableMetaData.setModel_states(ModelStates.FINISHED);
			parentNode.setUserObject(tableMetaData);
			for(int i=0;i<parentNode.getChildCount();i++){
				refreshAllModelTree((DefaultMutableTreeNode)parentNode.getChildAt(i),false);
			}
		}else{
			for(int i=0;i<parentNode.getChildCount();i++){
				refreshAllModelTree((DefaultMutableTreeNode)parentNode.getChildAt(i),false);
			}
		}
	}

	/**
	 * 刷新部分数据
	 * @param parentNode
	 * @param isRoot
	 */
	private void refreshPartModelTree(DefaultMutableTreeNode parentNode,boolean isRoot){
		if(!isRoot){
			BlkTableMetaData tableMetaData = (BlkTableMetaData)parentNode.getUserObject();
			if(execute_all_success_data.contains(tableMetaData.getTablemetadata_id())){
				tableMetaData.setModel_states(ModelStates.FINISHED);
				parentNode.setUserObject(tableMetaData);
			}
			for(int i=0;i<parentNode.getChildCount();i++){
				refreshAllModelTree((DefaultMutableTreeNode)parentNode.getChildAt(i),false);
			}
		}else{
			for(int i=0;i<parentNode.getChildCount();i++){
				refreshAllModelTree((DefaultMutableTreeNode)parentNode.getChildAt(i),false);
			}
		}
	}

	/**
	 * 提交完成后，整体刷新数结构
	 */
	private void refreshModelTree(boolean is_all_submit){
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		if(is_all_submit){
			//全部提交,刷新整个树结构，标记树结构状态为完成
			//获取根节点
			DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)treePanel.getTree().getModel().getRoot();
			refreshAllModelTree(rootNode,true);

		}else{
			//部分提交
			//获取根节点
			DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)treePanel.getTree().getModel().getRoot();
			refreshPartModelTree(rootNode,true);
		}
		//刷新选中的节点属性信息
		DefaultMutableTreeNode selNode = treePanel.getSelectTreeNode();
		if(selNode !=null){
			AttrPanel.newInstance().refreshTableData((BlkTableMetaData)selNode.getUserObject());
		}
		execute_all_success_data.clear();
	}
}
